﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using WPRD.Interfaces;

namespace WPRD.Behaviors
{
    public class ValidationExceptionBehavior : Behavior<FrameworkElement>
    {
        /// <summary>
        /// 验证错误数
        /// </summary>
        private int _validationErrorCount = 0;

        /// <summary>
        /// 重写附加响应函数
        /// </summary>
        protected override void OnAttached()
        {
            //附加对象时，给对象增加一个监听验证错误事件的能力，注意该事件是冒泡的
            this.AssociatedObject.AddHandler(Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(this.OnValidationError));
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <returns></returns>
        private IValidationExceptionHandler GetValidationExceptionHandler()
        {
            if (this.AssociatedObject.DataContext is IValidationExceptionHandler)
            {
                IValidationExceptionHandler handler = (IValidationExceptionHandler)this.AssociatedObject.DataContext;
                return handler;
            }
            return null;
        }

        /// <summary>
        /// 验证错误响应函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnValidationError(object sender, ValidationErrorEventArgs e)
        {
            IValidationExceptionHandler handler = GetValidationExceptionHandler();
            if (handler == null)
                return;
            if (e.Action == ValidationErrorEventAction.Added)
            {
                _validationErrorCount++;
            }
            else if (e.Action == ValidationErrorEventAction.Removed)
            {
                _validationErrorCount--;
            }
            handler.IsValid = _validationErrorCount == 0;
        }
    }
}
